package com.polaris.live.ui.message.widget.single_message

import android.view.View
import com.bumptech.glide.Glide
import com.polaris.live.R
import com.polaris.live.adapter.MessageAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.databinding.MessageItemSystemTextBinding
import com.polaris.live.im.db.entity.MessageEntity
import com.polaris.live.utils.image.loadImage
import com.polaris.live.utils.route.RouterUtils

/**
 * 系统消息的文本
 *
 * @author Created by lucas on 2023/10/25 10:42
 * @since 1.0.0
 */
class MessageSystemTextItemHolder(
    adapter: MessageAdapter,
    binding: MessageItemSystemTextBinding
) : AbstractMessageItemHolder<MessageItemSystemTextBinding>(adapter, binding) {

    override fun bind(item: MessageEntity) {
        mBinding.apply {
            bindCommon(
                item,
                layoutTime.messageTextTime,
                layoutLeft,
                layoutRight,
                layoutLeftAvatar.avAvatar,
                layoutRightAvatar.avAvatar,
                layoutLeftAvatar.avFv,
                layoutRightAvatar.avFv,
                null,
                null,
                ivState,
                tvError
            )
        }

        if (item.sender == UserManager.getUser().userId) {
            setTextRight(item)
        } else {
            setTextLeft(item)
        }
    }

    private fun setTextLeft(item: MessageEntity) {
        mBinding.apply {
            item.payloadBean.also {
                if (it?.banner.isNullOrEmpty()) {
                    ivBanner.visibility = View.GONE

                    clContent.setBackgroundResource(R.drawable.left_top2_r12_back_ffffff)
                } else {
                    ivBanner.visibility = View.VISIBLE

                    clContent.setBackgroundResource(R.drawable.left_round12_back_ffffff)

                    Glide.with(ivBanner)
                        .loadImage(it?.banner)
                        .into(ivBanner)
                }

                if (it?.highlight != null) {
                    RouterUtils.handleRouterText(
                        tvLeftText,

                        item.content,
                        it.highlight,
                        it.router ?: emptyMap()
                    )
                } else {
                    tvLeftText.text = item.content
                }
            }

            val footer = item.payloadBean?.footer
            if (footer.isNullOrEmpty()) {
                tvFooter.visibility = View.GONE
            } else {
                tvFooter.visibility = View.VISIBLE
                tvFooter.text = footer
            }
        }
    }

    private fun setTextRight(item: MessageEntity) {
        mBinding.apply {
            rightContent.text = item.content
        }
    }
}